package org.datacoder.geocoding.jurisdiction

import org.datacoder.util.*

class SenatorialDistrictService {

    def jurisdictionService
    def stateService

    static transactional = true

    /* CRUD */
    public SenatorialDistrict create(SenatorialDistrict sd) throws DAOException{
        sd.state.addToSenatorialDistricts(sd)
        stateService.save(sd.state)
        save(sd)
        return sd
    }
    public void save(SenatorialDistrict sd) throws DAOException{
        ServiceUtils.save(sd)
    }
    public void save(SenatorialDistrict sd, boolean flush) throws DAOException{
        ServiceUtils.save(sd, flush)
    }
    public void delete(SenatorialDistrict sd){
        if(sd == null){
            return
        }
        if(sd.state?.senatorialDistricts?.contains(sd)){
            sd.state.senatorialDistricts.remove(sd)
        }
        sd.delete(flush:true)
    }
    public SenatorialDistrict merge(SenatorialDistrict sd){
        return sd.merge()
    }
    public SenatorialDistrict get(String sdId){
        return get(Long.parseLong(sdId))
    }
    public SenatorialDistrict get(long sdId){
        return SenatorialDistrict.get(sdId)
    }
    public Set<SenatorialDistrict> getAll(){
        return SenatorialDistrict.findAll()
    }
    /* END CRUD */

    public SenatorialDistrict getByNameAndStateOrCreate(String name, State state, String longName){
        SenatorialDistrict sd = getByNameAndState(name, state)
        if(sd == null){
            sd = new SenatorialDistrict(
                name:name,
                longName:longName,
                state:state
            )
            sd = create(sd)
        }
        return sd
    }

    public SenatorialDistrict getByNameAndState(String name, State state){
        SenatorialDistrict sd = SenatorialDistrict.findByNameAndState(name, state)
        return sd
    }
}

